using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Principal;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

using SqlWebAdmin.CSharp;

public partial class Credentials : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
			object error = Request.QueryString["Error"];

			if (error != null)
			{
				lblError.Visible = true;
				lblError.Text = error.ToString();
			}
			else
			{
				lblError.Visible = false;
			}
			
			lblLogoutInfo.Visible = false;
            lblLoginInfo.Visible = true;

            txtServer.Text = "(local)";
            Session["serverName"] = txtServer.Text;

            if (ddlAuthType.SelectedIndex == 0)
            {
                txtUsername.Text = WindowsIdentity.GetCurrent().Name;
            }
            else
            {
                txtUsername.Text = "sa";
            }
        }

        if (Request.QueryString["error"] != null)
        {
            switch (Request.QueryString["error"])
            {
                case "sessionexpired":
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">Your session has expired. Please enter your login information again.</div>";
                    break;
                case "userinfo":
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">Invalid username and/or password, or server does not exist.<br>Also, please ensure that SQL Server Authentication is enabled on the server.</div>";
                    break;
                default:
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">An unknown error has occured.</div>";
                    break;
            }
        }
        else
        {
            if (Request.QueryString["action"] == "logout")
            {
                lblLogoutInfo.Visible = true;
                lblLoginInfo.Visible = false;
            }
        }
    }


    protected void ddlAuthType_SelectedIndexChanged(object sender, EventArgs e)
    {
		if (ddlAuthType.SelectedIndex == 0)
		{
			txtUsername.Text = WindowsIdentity.GetCurrent().Name;
			txtUsername.Enabled = false;
			txtPassword.Enabled = false;
			txtServer.Enabled = true;
			txtConnectionString.Enabled = false;
			connStringValidator.Enabled = false;
		}
		else if (ddlAuthType.SelectedIndex == 1)
		{
			txtUsername.Enabled = true;
			txtPassword.Enabled = true;
			txtUsername.Text = "sa";
			txtServer.Enabled = true;
			txtConnectionString.Enabled = false;
			connStringValidator.Enabled = false;
		}
		else if (ddlAuthType.SelectedIndex == 2)
		{
			txtUsername.Enabled = false;
			txtPassword.Enabled = false;
			txtServer.Enabled = false;
			txtConnectionString.Enabled = true;
			connStringValidator.Enabled = true;
		}

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            string serverName = txtServer.Text.Trim();
            string userName = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            Server smoServer = new Server(serverName);
            try
            {
                if (ddlAuthType.SelectedIndex == 1)
                {
                    smoServer.ConnectionContext.LoginSecure = false;
                    smoServer.ConnectionContext.Login = userName;
                    smoServer.ConnectionContext.Password = password;
                }

				if (ddlAuthType.SelectedIndex == 2)
				{
					smoServer.ConnectionContext.ConnectionString = txtConnectionString.Text;
				}

                ServerVersion serverVersion = smoServer.ConnectionContext.ServerVersion;


				Profile.ServerName = serverName;
				
                Session["serverName"] = serverName;
                Session["useIntegratedSecurity"] = smoServer.ConnectionContext.LoginSecure;
                Session["username"] = userName;
                Session["password"] = Encryption.Current().Encrypt(password);

				//FormsAuthentication.SetAuthCookie("SQL$" + userName, false);
				string redirUrl = string.Empty; 
				object qsru = Request.QueryString["RU"];
				// take a look and see if there is any redirect url for us.  if not redirect to home.
				if (qsru == null)
				{
					redirUrl = "~/home.aspx";
				}
				else
				{
					redirUrl = qsru.ToString();
				}
				// get the connection string, we can use this to rehydrate the connection to SMO
				string connString = smoServer.ConnectionContext.ConnectionString;
				Encryption crypt = Encryption.Current();
				// encrypt the connection string
				string cryptedConnString = crypt.Encrypt(connString);

				// store it in profile
				Profile.ConnectionString = cryptedConnString;
				Profile.Save();

				Response.Redirect(redirUrl);

            }
            catch (Microsoft.SqlServer.Management.Smo.SmoException smoEx)
            {
                lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">" + HttpUtility.HtmlEncode(Common.ConcatenateExceptions(smoEx)) + "</div>";
                lblError.Visible = true;
            }
            catch (Exception ex)
            {
				lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">Error: " + HttpUtility.HtmlEncode(Common.ConcatenateExceptions(ex)) + "</div>";
				lblError.Visible = true;
            }

            
        }

    }
}
